package com.mxpio.erp.common.plan.service.impl;

import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mxpio.erp.common.jpa.model.BizPlan;
import com.mxpio.erp.common.plan.policy.PlanContext;
import com.mxpio.erp.common.plan.policy.PlanPolicy;
import com.mxpio.erp.common.plan.provider.PlanContextProvider;
import com.mxpio.erp.common.plan.service.PlanService;

@Service
public class PlanServiceImpl implements PlanService {
	
	@Autowired(required = false)
	private List<PlanContextProvider> planContextProviders;

	/**
	 * 计划执行
	 */
	@Override
	@Transactional(readOnly = false)
	public PlanContext execute(BizPlan plan, PlanPolicy policy) {
		// 通用OrderContext初始化
		PlanContext context = PlanContext.init(plan);
		policy.config(context);
		// 遍历匹配的 Context提供器 补充Context信息
		if(CollectionUtils.isNotEmpty(planContextProviders)){
			for(PlanContextProvider provider : planContextProviders){
				if(provider.supports(plan.getClass())){
					provider.provide(context);
				}
			}
		}
		if(CollectionUtils.isEmpty(context.getErrors())){
			// 执行订单
			policy.apply(context);
		}
		
		return context;
	}

}
